import React, { useState, useEffect } from 'react'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import {
  Card,
  Tabs,
  Button,
  Table,
  Popover,
  Badge,
  message,
  Input,
  Popconfirm,
  Tag,
  Divider
} from 'antd'
import {
  BANNER_KEY,
  PRODUCT_KEY,
  passiveFetchHandler,
  defaultListRes,
  getDataSource,
  tabs,
  defaultListReqParams,
  generatePagination,
  getType,
  deleteProductHandler,
  deleteBannerHandler,
  reorderProductHandler
} from './notDirectUiLogic'
import CreateModal from './components/modal'
import styles from './index.module.less'

const { TabPane } = Tabs
const colors = [
  { color: 'grey', text: '' },
  { color: '#108ee9', text: '全新' },
  { color: '#1c8dde', text: '99新' },
  { color: '#278bd2', text: '95新' },
  { color: '#3b86bb', text: '9成新' },
  { color: '#4583af', text: '8成新' },
  { color: '#5587ab', text: '7成新' }
]

const SecondHand = props => {
  const [tabActiveKey, setActiveTabKey] = useState(BANNER_KEY)
  const [loading, setLoading] = useState(false) // 设置是否处于加载的过程中
  const [listReqParams, setListReqParams] = useState(defaultListReqParams) // 请求列表接口的页码参数挂载点，即包括banner模块，也包括商品模块
  const [listRes, setListRes] = useState(defaultListRes) // 列表接口所返回的响应数据挂载点，即包括banner模块，也包括商品模块
  const [showModal, setShowModal] = useState(false) // 设置是否显示弹窗
  const [modifyObj, setModifyObj] = useState(null) // 修改的对象
  const [refresh, setRefresh] = useState(1) // 设置是否需要重新拉取数据

  /**
   * 切换tab的时候触发
   * @param {*} val : tab的key名
   */
  const onTabChange = val => {
    setActiveTabKey(val)
  }

  /**
   * 修改banner时触发
   */
  const modifyHandler = record => {
    const channels = record.channel
    if (typeof channels === 'string') {
      if (channels === '') record.channel = []
      else record.channel = channels.split('&')
    }
    setModifyObj(record)
    setShowModal(true)
  }

  const newHandler = () => {
    setModifyObj({})
    setShowModal(true)
  }

  // 删除商品的回调方法
  const deleteProduct = record => {
    const sucDelCb = () => {
      message.success('删除商品成功')
      delLastItemHandler(PRODUCT_KEY)
    }
    const { id } = record
    deleteProductHandler(id, sucDelCb)
  }

  const deleteBanner = record => {
    const sucDelCb = () => {
      message.success('删除Banner成功')
      delLastItemHandler(BANNER_KEY)
    }
    const { id } = record
    deleteBannerHandler(id, sucDelCb)
  }

  // 删除最后一个元素的修复方法
  const delLastItemHandler = key => {
    const datas = getDataSource(listRes, key)
    if (datas.length === 1) {
      // 说明的确是删除最后一个元素
      pageNumberChangeHandler(1) // 初始化为第1页
    } else {
      refreshHandler()
    }
  }

  // 修改商品的排序
  const reOrderProduct = (productObj = {}) => {
    const { id, sort } = productObj
    if (!id || !sort) return
    const data = { id, sort }
    const reOrderSuccess = () => {
      message.success('操作成功')
      refreshHandler()
    }
    reorderProductHandler(data, props, reOrderSuccess)
  }

  /**
   * 改变商品排列序号的时候触发
   * @param {*} event
   * @param {*} productobj
   */
  const changeSortHandler = (event, productObj) => {
    const orderNum = event.target.value // 所输入的排序号
    const oldProductListRes = (listRes && listRes[PRODUCT_KEY]) || {} // 获取商品列表接口所返回的数据
    const productList = getDataSource(listRes, PRODUCT_KEY)
    const { id } = productObj
    const newProductList = productList.map(obj => {
      if (obj.id === id) return { ...obj, sort: orderNum }
      return obj
    })
    const newListRes = { ...listRes }
    newListRes[PRODUCT_KEY] = {
      ...oldProductListRes,
      records: newProductList
    }
    setListRes(newListRes)
  }

  /**
   * 生成table的列信息
   * @param {String} key : banner的key 或者 商品的key
   */
  const generateColumns = key => {
    if (key === BANNER_KEY)
      return [
        { title: 'ID', dataIndex: 'id', key: 'id' },
        { title: 'Banner名称', dataIndex: 'title', key: 'title' },
        {
          title: 'Banner图片',
          dataIndex: 'imgSrc',
          key: 'imgSrc',
          render: val => {
            const renderImg = clsName => (
              <img className={styles[clsName]} src={val} />
            )
            return (
              <Popover content={renderImg('maxPhoneImg')}>
                {renderImg('smPhoneImg')}
              </Popover>
            )
          }
        },
        { title: '跳转链接', dataIndex: 'link', key: 'link' },
        {
          title: '上架渠道',
          dataIndex: 'channelName',
          key: 'channelName',
          render: (str = '') => {
            const platformList = str.split('&')
            return (
              <div>
                {platformList.map(str => (
                  <div key={str}>{str}</div>
                ))}
              </div>
            )
          }
        },
        { title: '上线时间', dataIndex: 'createTime', key: 'createTime' },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          render: val => (
            <Badge
              status={val ? 'success' : 'default'}
              text={val ? '有效' : '失效'}
            />
          )
        },
        { title: '排序', dataIndex: 'sort', key: 'sort', width: 60 },
        {
          title: '操作',
          dataIndex: '',
          key: 'ope',
          align: 'center',
          render: (_, record) => {
            return (
              <div className={styles.opeBtnWrapper}>
                <a onClick={() => modifyHandler(record)}>修改</a>
                {/* <Button onClick={() => modifyHandler(record)} type="link" size="small">修改</Button> */}
                <Divider type="vertical" />
                <Popconfirm
                  title="确定删除该Banner吗?"
                  onConfirm={() => deleteBanner(record)}
                >
                  <a>删除</a>
                  {/* <Button type="link" size="small">删除</Button> */}
                </Popconfirm>
              </div>
            )
          },
          width: 150
        }
      ]
    // 商品的表格配置数据
    return [
      { title: '商品编号', dataIndex: 'productId', key: 'productId' },
      { title: '商品名称', dataIndex: 'productName', key: 'productName' },
      { title: '店铺名称', dataIndex: 'shopName', key: 'shopName' },
      {
        title: '排序',
        dataIndex: 'sort',
        key: 'sort',
        render: (val, record) => {
          return (
            <Input
              value={val}
              onChange={event => changeSortHandler(event, record)}
              onPressEnter={() => reOrderProduct(record)}
            />
          )
        }
      },
      {
        title: '新旧',
        dataIndex: 'oldNewDegree',
        key: 'oldNewDegree',
        render: val => {
          const obj = colors[val]
          return <span>{obj.text}</span>
          // return <Tag color={obj.color}>{obj.text}</Tag>
        }
      },
      { title: '价格', dataIndex: 'sale', key: 'sale' },
      {
        title: '操作',
        dataIndex: '',
        key: 'ope',
        align: 'center',
        render: (val, record) => {
          return (
            <Popconfirm
              title="确定删除该商品吗?"
              onConfirm={() => deleteProduct(record)}
            >
              <a>删除</a>
              {/* <Button size="small" type="link">删除</Button> */}
            </Popconfirm>
          )
        }
      }
    ]
  }

  // 更新listReqParams数据
  const applyPaginationEffects = effectObj => {
    let newListReq = {
      ...listReqParams,
      [tabActiveKey]: {
        ...listReqParams[tabActiveKey],
        ...effectObj
      }
    }
    setListReqParams(newListReq) // 更新分页器数据
  }
  /**
   * 改变页码的时候触发
   */
  const pageNumberChangeHandler = pageNumber => {
    const effectObj = { pageNumber }
    applyPaginationEffects(effectObj)
  }
  // 改变每页条数，此时同样也需要改变页码
  const pageSizeChangeHandler = (_, pageSize) => {
    const effectObj = { pageNumber: 1, pageSize }
    applyPaginationEffects(effectObj)
  }
  // 分页器的配置数据
  const pagination = {
    ...generatePagination(listReqParams, listRes, tabActiveKey), // 生成基本的pagination配置数据
    onChange: pageNumberChangeHandler,
    onShowSizeChange: pageSizeChangeHandler
  }

  const refreshHandler = () => setRefresh(refresh + 1)

  /**
   * 当切换tab菜单的时候，获取列表数据
   */
  useEffect(() => {
    const succesCb = data => {
      const newListRes = { ...listRes }
      newListRes[tabActiveKey] = data
      setListRes(newListRes)
      setLoading(false)
    }
    setLoading(true)
    passiveFetchHandler(props, listReqParams, tabActiveKey, succesCb)
  }, [tabActiveKey, listReqParams, refresh, props, listRes])

  return (
    <PageHeaderWrapper>
      <Card bordered={false}>
        <Tabs
          activeKey={tabActiveKey}
          animated={false}
          onChange={onTabChange}
          tabBarExtraContent={
            <Button type="primary" onClick={newHandler}>
              新增
            </Button>
          }
        >
          {tabs.map(tabObj => (
            <TabPane tab={tabObj.ui} key={tabObj.key}>
              <Table
                columns={generateColumns(tabObj.key)}
                loading={loading}
                tableLayout="fixed"
                dataSource={getDataSource(listRes, tabObj.key)}
                rowKey={record => record.id}
                pagination={pagination}
              />
            </TabPane>
          ))}
        </Tabs>
      </Card>
      <CreateModal
        visible={showModal}
        tabKey={tabActiveKey}
        hideModal={() => setShowModal(false)}
        type={getType(props)}
        modifyObj={modifyObj}
        refreshListCb={refreshHandler}
      />
    </PageHeaderWrapper>
  )
}

export default SecondHand
